package jgl.vajra.operator.widget.manager;

import jgl.vajra.operator.R;
import jgl.vajra.operator.widget.bean.BaseRequestData;
import jgl.vajra.operator.widget.utils.UIUtils;
import jgl.vajra.operator.widget.retrofithelper.rxexception.DefaultErrorBundle;
import jgl.vajra.operator.widget.retrofithelper.rxexception.ErrorManager;
import jgl.vajra.operator.widget.retrofithelper.rxexception.ServerException;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

/**
 * Created by Administrator on 2016/11/24 0024.
 */
public class RxJavaDataManager {
    // 将访问网络成功拿到的observable对象预处理通过compose方法进行转换
    public static <T> ObservableTransformer<BaseRequestData<T>, T> handleResult() {
        return new ObservableTransformer<BaseRequestData<T>, T>() {
            @Override
            public ObservableSource<T> apply(Observable<BaseRequestData<T>> upstream) {
                final Observable<T> observable = upstream.flatMap(new Function<BaseRequestData<T>, ObservableSource<T>>() {
                    @Override
                    public ObservableSource<T> apply(BaseRequestData<T> tBaseRequestData) throws Exception {
                        if (tBaseRequestData == null) {
                            return Observable.error(new ServerException(-1, UIUtils.getString(R.string.service_error)));
                        } else if (tBaseRequestData.code == 200) {
                            return createObservable(tBaseRequestData.data);
                        } else {
                            return Observable.error(new ServerException(tBaseRequestData.code, String.valueOf(tBaseRequestData.msg)));
                        }
                    }
                });
                observable.subscribeOn(io.reactivex.schedulers.Schedulers.io());
                return observable;
            }
        };
    }

    private static <T> Observable<T> createObservable(final T data) {
        return Observable.create(new ObservableOnSubscribe<T>() {
            @Override
            public void subscribe(ObservableEmitter<T> emitter) throws Exception {
                try {
                    emitter.onNext(data);
                    emitter.onComplete();
                } catch (Exception e) {
                    ErrorManager.handleError(new DefaultErrorBundle(e));
                    emitter.onError(e);
                }
            }
        });
    }

}
